<template>
  <div class="page-main" v-title data-title="标准样管理列表">
    <div class="banner"><span>标准样管理列表</span></div>
     <FixedMenu menuClass="std-menu">
          <div class="fixed-menu std-menu">
       
            <div  class="functionMould" style="background-color: #ffffff" @click="handAction('add')">
              <a-icon type="file-add" class="menu-icon" />
              <span> 标准样制定</span>
            </div>
          
            <div  v-has="'stdSample:batch'" class="functionMould" style="background-color: #ffffff" @click="handAction('addBatch')">
              <a-icon type="file-add" class="menu-icon" />
              <span> 批量导入</span>
            </div>
            <div v-has="'stdSample:type'"  class="functionMould" style="background-color: #ffffff" @click="handAction('stdType')">
              <a-icon type="hdd" class="menu-icon" />
              <span> 目录管理</span>
            </div>
            
        </div>
    </FixedMenu> 
    <div class="container containerMore" style="padding-top: 16px;">
    
      <div class="container-bg" style="    padding: 0;">
       
       

      <div class="data-main " :class="{'shrinkage': shrinkageFlag}">          
        <div class="box-left ant-table-scroll" >
          <div class="tree-title">
            <span class="bold">目录</span>
            <a-icon type="menu-fold" @click="shrinkageFlag = !shrinkageFlag"  :title="!shrinkageFlag? '收缩目录' : '展开目录'"/>
          </div>
          <div class="tree" v-if="!shrinkageFlag"> 
            <a-input-search allow-clear style="margin-bottom: 8px" v-model="searchValue" placeholder="搜索目录" @search="onChangeTree" />
            <a-tree                             
              :tree-data="treeData"
              :selectedKeys="treeSelectedKeys"
              @select="onSelectClass"
              @expand="onExpand"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :replaceFields="{children:'children', title:'name', key:'id' }"
            >
             <template slot="title" slot-scope="{title}">
                <span v-if="title.indexOf(searchValue) > -1">
                  {{title.substr(0, title.indexOf(searchValue))}}
                  <span style="color: #f50">{{searchValue}}</span>
                  {{title.substr(title.indexOf(searchValue) + searchValue.length)}}
                </span>
                <span v-else>{{title}}</span>
              </template>
            </a-tree>
          </div>
        </div>
        <div class="box-right" style="padding:0 16px;">
          <div class="trademark-nav"  style="margin-top: 0;" :class="{'trademark-nav-hidden': toggleSearchStatus}">      
          <div class="projec-class-box clearFix  projec-class-input">
              <div>
                <ul class="projec-class-list clearFix" >
                  <li :class="['hoverShow',{clickShow:customParam.dataType==v.code}]" @click="handleTab('dataType',v.code) " v-for="(v,i) in dict.dataType" :key="i">{{v.name}}</li>
                </ul>
              </div>
          </div>
         
      </div>
           <div class="header" style="padding: 8px 0;">
          <a-row type="flex" justify="space-between" align="middle">
            <a-col>
              <a-tooltip title="自动作废任务和待执行任务没有生效时使用">
              <a-button type="primary" v-has="'stdSample:job'" class="hte-btn" @click="handAction('job')" >执行任务</a-button>
              </a-tooltip>
              <a-button type="primary" v-has="'stdSample:lab'"  class="hte-btn" @click="handAction('lab')">同步实验室数据</a-button>
              <a-button class="hte-btn" @click="handleExportXls('标准样制定')">导出</a-button>
              <a-button class="hte-btn" @click="searchReset">刷新</a-button>
            </a-col>
            <a-col class="input-ground">
              <a-input-group compact>
                <a-select v-model="searchField" @change="changeKeywordType" style="min-width:160px">
                  <a-select-option value="t.std_no">感官标准样编号</a-select-option>
                  <a-select-option value="t.mara_matnr">物料编号</a-select-option>
                  <a-select-option value="mara.maktx">物料名称</a-select-option>
                  <a-select-option value="applyMatnr">适用物料编号</a-select-option>
                  <a-select-option value="applyMaktx">适用物料名称</a-select-option>
                </a-select>
                <a-input-search
                  v-model="queryParam.keyword"
                  @search="doSearch"
                  allowClear
                  placeholder="请输入关键词检索"
                />
               
              </a-input-group>
              <a-button class="hte-btn del-btn" @click="visibleModel = true">高级查询</a-button>
            </a-col>
          </a-row>
        </div>
          <a-table
            class="hte-table-content"
            :scroll="{ x: 1720 }"
            :columns="columns"
            :data-source="dataSource"
            :pagination="ipagination"
            :loading="loading"
            rowKey="id"
            size="middle"
            @change="handleTableChange"
          >            
          <template slot="filterStatus" slot-scope="text, record,index">       
              <span>{{text|stdSampleStatusFilter}}</span>
                
            </template>
              <template slot="link" slot-scope="text, record,index">       
              <span class="clickspan" @click="handAction('link', record)">{{ text }}</span>
            </template>
           
          
           <span slot="action" slot-scope="text, record">
              <a @click="handAction('upateDet',record)">更新明细</a>
              <a-divider type="vertical" />
              <a @click="handAction('his',record)">历史版本</a>
            </span>
             <template slot="target" slot-scope="text, record">
              <span :class="{'targetRed': !!text&& text.indexOf('A')<0}" class="text-over" :title="text">{{ text }}</span>
            </template>
            <template slot="pushTime" slot-scope="text, record">
              <span >{{ record.pushTime }}</span>
            </template>
            <template slot="submitTime" slot-scope="text, record">
              <span >{{ record.submitTime }}</span>
            </template>
            <template slot="executeTime" slot-scope="text, record">
              <span >{{ record.executeTime }}</span>
            </template>
            <template slot="autoAbolishTime" slot-scope="text, record">
               <span >{{ record.autoAbolishTime }}</span>
            </template>
              <template slot="abolishTime" slot-scope="text, record">
               <span >{{ record.abolishTime }}</span>
            </template>
            <template slot="textOver" slot-scope="text">
              <span class="text-over" :title="text">{{text}}</span>
            </template>
          </a-table>
        </div>
         </div>
      </div>
      <table-select-modal :params="lab.params"  :title="lab.title"  :listUrl="lab.list" rowKey="id"  :showSelection="false" :isAllSelect="false" 
        :importColumns="lab.colums" ref="labRef" ></table-select-modal>
    </div>
    
    <a-back-top class="backtodom" />
    <!-- 高级查询 -->
    <advanced-search
      :dataForm.sync="queryParam"
      :visible="visibleModel"
      ref="advanced"
      :formCol="queryParamCol"
      @ok="callBackResult"
      @reset="resetResulte"
      @close="closeResulte"
    >
    </advanced-search>
    
  </div>
</template>
<script>
import Vue from 'vue'
import { getAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { USER_INFO, ACCESS_TOKEN } from '@/store/mutation-types'
import { stdSampleStatusFilter ,stdSampleStatusTbFilters} from '@/utils/filter'
  const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
export default {
  name: 'StdSampleList',
  mixins: [JeecgListMixin],
  components: {
    AdvancedSearch: () => import('@/components/tools/AdvancedSearch'),
    FixedMenu: () => import('@/components/tools/FixedMenu'),
    TableSelectModal: () => import('@/components/tools/TableSelectModal'),
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'StdSampleList',
      },
      radioType: '',
      currUser: Vue.ls.get(USER_INFO).username,
      filteredInfo:{},
      
      url: {
        list: '/stdSample/list', // 搜索
        exportXlsUrl: '/stdSample/exportXls', // 导出
        getTree: '/stdSampleType/getTree',
        stdSampleJob: '/stdSample/stdSampleJob',
        updateLabData:'/stdLab/updateLabData',
      },
      // 高级查询
      visibleModel: false,
      searchField: 't.std_no',
      queryParam: {
        scopeFlag: true,
        searchField: 't.std_no',
      },
      queryParamCol: [
        { type: 'input', model: 'stdNo', label: '感官标准样编号' },
        { type: 'input', model: 'maraMatnr', label: '物料编号' },
        { type: 'input', model: 'maraMaktx', label: '物料名称' },
        { type: 'input', model: 'lab', label: '质检实验室' },
        
      ],
      isorter: {
        column: 't.push_time',
        order: 'desc',
      },
      // 导入
      exportXlsTemplateUrl: 'templates/excel/brandSimilitudeGroupTemplate.xlsx', //导入模板
      excelVisible: false,
      excelConfirmLoading: false,
      columnsExcel: [],
      customParam: { scopeFlag: true, parentId: 0, dataType: 4 , searchField: 't.std_no',},
      shrinkageFlag: false,
      treeData: [],
      dataList: [],
      treeSelectedKeys: [],
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      dict: {
        orderList0: [], // 准样内容指标
        dataType: [
          { code: 4, name: '生效中' },
          // { code: 1 , name: '草稿' },
          { code: 2 , name: '审批中' },
          { code: 3 , name: '待执行' },
          { code: 9 , name: '审批不通过' },
          { code: 10 , name: '已作废' },
          { code: 0, name: '我的申请' },
        ], // 数据类型
      },
      lab:{
        title:'标准样更新',
        list:'/stdSampleLabup/list',
        params:{},
        colums:[
           {
            title:'更新后的标准样编号',
            align:"center",
            dataIndex: 'qmsNo',
            //width:'25%',
          },
          {
            title:'实验室编号',
            align:"center",
            dataIndex: 'labCode',
            width:'25%',
          },
           {
            title:'实验室名称',
            align:"center",
            dataIndex: 'lab',
            width:'20%',
          },
          {
            title:'更新时间',
            align:"center",
            dataIndex: 'updateTime',
            width:'20%',
          }
        ],
      },
    }
  },
  filters: {
    stdSampleStatusFilter,
  },
  computed:{
    columns() {
      let {  filteredInfo,customParam } = this;
      filteredInfo = filteredInfo || {};

      var statusTbFilters = []
      if(customParam.dataType === 0){
          statusTbFilters = stdSampleStatusTbFilters
      }
      const columns = [
        {
          title: '标准样编号',
          dataIndex: 'stdNo',
          width: 150,
          align: 'left',
          scopedSlots: { customRender: 'link' },
        },
        { title: '物料编号', dataIndex: 'maraMatnr', width: 180, align: 'left',scopedSlots: { customRender: 'textOver' } },
        { title: '物料名称', dataIndex: 'maraMaktx', width: 120, align: 'left' ,scopedSlots: { customRender: 'textOver' }},
        { title: '色泽评级评分', dataIndex: 'colorText', width: 100, align: 'left',scopedSlots: { customRender: 'target' },},
        {
          title: '香气评级评分',
          dataIndex: 'aromaText',
          width: 120,
          align: 'left',
          scopedSlots: { customRender: 'target' },
        },
        { title: '滋味评级评分', dataIndex: 'tasteText', width: 180, align: 'left',scopedSlots: { customRender: 'target' } },
        { title: '体态评级评分', dataIndex: 'postureText', width: 120, align: 'left',scopedSlots: { customRender: 'target' }},
        { title: '适用物料编号', dataIndex: 'applyMatnr', width: 180, align: 'left',scopedSlots: { customRender: 'textOver' } },
        { title: '适用物料名称', dataIndex: 'applyMaktx', width: 180, align: 'left',scopedSlots: { customRender: 'textOver' } },
        { title: '质检实验室', dataIndex: 'lab', width: 120, align: 'left',scopedSlots: { customRender: 'textOver' } },
        { title: '目录分类', dataIndex: 'stdTypeName', width: 120, align: 'left',scopedSlots: { customRender: 'textOver' } },

        {
          title: '状态',
          dataIndex: 'status',
          width: 100,
          align: 'left',
          scopedSlots: { customRender: 'filterStatus' },
           filters: statusTbFilters,
           filteredValue: filteredInfo.status || null,
        },
        
        { title: '标准样类型', dataIndex: 'stdMoldName', width: 180, align: 'left' },
        
     
        { title: '编制人', dataIndex: 'createUser', width: 100, align: 'left' },
        {
          title: '提交日期',
          dataIndex: 't.submitTime',
          width: 100,
          align: 'left',
          scopedSlots: { customRender: 'submitTime' },
          sorter: (a, b) => new Date(a.submitTime).getTime() - new Date(b.submitTime).getTime(),
        },
        {
          title: '发布日期',
          dataIndex: 't.push_time',
          width: 100,
          align: 'left',
          scopedSlots: { customRender: 'pushTime' },
          sorter: (a, b) => new Date(a.pushTime).getTime() - new Date(b.pushTime).getTime(),
        },
        {
          title: '执行日期',
          dataIndex: 't.execute_time',
          width: 100,
          align: 'left',
          scopedSlots: { customRender: 'executeTime' },
          sorter: (a, b) => new Date(a.executeTime).getTime() - new Date(b.executeTime).getTime(),
        },
        // {
        //   title: '废止日期',
        //   dataIndex: 't.abolish_time',
        //   width: 100,
        //   align: 'left',
        //   scopedSlots: { customRender: 'abolishTime' },
        //   sorter: (a, b) => new Date(a.abolishTime).getTime() - new Date(b.abolishTime).getTime(),
        // },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ]
      return columns;
    },
  },
  mounted() {
    this.columnsExcel = this.columns
    this.getTree()
  },
  methods: {
    refresh() {
      this.queryParam = Object.assign(this.queryParam, { scopeFlag: true })
      this.loadData(1)
    },
    doSearch() {
      this.queryParam = Object.assign(this.queryParam, { scopeFlag: true })
      this.loadData(1)
    },
    changeKeywordType(value) {
      this.$set(this.queryParam, 'searchField', value)
       this.$set(this.customParam, 'searchField', value)
    },
    /**
     * 高级搜索
     */
    callBackResult() {
      this.visibleModel = false
      this.doSearch()
    },
    closeResulte() {
      this.visibleModel = false
    },
    resetResulte() {
      this.queryParam = { scopeFlag: true }
      this.doSearch()
    },
    /**
     * 操作
     */
    handAction(type, id) {
       const that = this
      switch (type) {
        case 'del':
          // 删除，可多选
         
          if (this.selectedRowKeys.length == 0) {
            this.$message.warning('请选择至少一条数据！')
            return
          }
          if (
            this.selectionRows.filter((item) => {
              return item.status > 1
            }).length > 0
          ) {
            this.$message.warning('删除失败请选择创建中状态删除！')
            return
          }
          this.$confirm({
            title: '确认删除',
            content: '请确认是否删除此信息?',
            onOk: function () {
              getAction(that.url.delBatch, { ids: that.selectedRowKeys.join(',') }).then((res) => {
                if (res.code == 200) {
                  that.$message.success('删除成功')
                  that.doSearch()
                } else {
                  that.$message.warning('删除失败:' + res.message)
                }
              })
            },
          })
          break
        case 'link':
          this.gotoDetail(`/stdSample/info?sampleBaseId=${id.id}`)
          break
          case 'upateDet':
          this.$set(this.lab,'params',{sampleBaseId:id.id})
          this.$set(this.lab,'title',`标准样${id.stdNo}更新明细`)
          this.$refs.labRef.open();
          break
         case 'his':
          this.gotoDetail(`/stdSample/hisList/${id.stdSampleId}/${id.id}`)
          break  
        case 'add':
          this.gotoDetail(`/stdSample/info`)
          break
        case 'addBatch':  
          this.gotoDetail(`/stdSample/listBatch`)
        break
        case 'stdType':
          this.gotoDetail(`/stdSample/typeList`)
          break
        case 'job':
          
           this.$confirm({
            title: '确认执行任务',
            content: '请确认是否执行任务?',
            onOk: function () {
              getAction(that.url.stdSampleJob,{}).then(res=>{
                  if (res.code == 200) {
                  that.$message.success('操作成功')
                  that.doSearch()
                } else {
                  that.$message.warning('操作异常:' + res.message)
                }
              })  
            },
          })
          break
           case 'lab':
          
           this.$confirm({
            title: '确认同步QMS实验室数据',
            content: '请确认是否同步QMS实验室数据?',
            onOk: function () {
              getAction(that.url.updateLabData,{}).then(res=>{
                  if (res.code == 200) {
                  that.$message.success('操作成功')
                  that.doSearch()
                } else {
                  that.$message.warning('操作异常:' + res.message)
                }
              })  
            },
          })
          break
        default:
          break
      }
    },
    gotoDetail(url) {
      let routeUrl = this.$router.resolve({
        path: url,
      })
      window.open(routeUrl.href, '_blank')
    },
    onSelectClass(selectedKeys, e) {
      if (e && !e.selected) {
        selectedKeys = this.treeSelectedKeys
      }
      this.customParam.parentId = selectedKeys[0]
      this.treeSelectedKeys = selectedKeys
      this.loadData(1)
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onChangeTree(value) {
      const that = this

      let expandedKeys = this.dataList.map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, that.treeData)
        }
        return null
      })
      expandedKeys = expandedKeys.filter((item, i, self) => {
        return item && self.indexOf(item) === i
      })
      Object.assign(that, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      })
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const key = node.key
        data[i].scopedSlots = { title: 'title' }
        this.dataList.push({ key, title: node.title })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    getTree() {
      getAction(this.url.getTree, {}).then((res) => {
        if (res.code == 200) {
          let treeData = res.result || []
          let allTree = { children: null, title: '全部', name: '全部', id: 0, key: 0, value: 0 }
          treeData.unshift(allTree)
          this.generateList(treeData)
          this.treeData = treeData
          this.customParam.parentId = 0
          this.treeSelectedKeys = [0]
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    handleTab(type, code) {
      this.customParam[type] = code
      this.filteredInfo = {}
      this.queryParam.statusIn = '';
      this.loadData(1)
    },
    handleTableChange(pagination, filters, sorter) {
            //分页、排序、筛选变化时触发
            //TODO 筛选
            console.log(pagination)
            if (Object.keys(sorter).length > 0) {
                this.isorter.column = sorter.field;
                this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
            }
            if (filters.status && filters.status.length > 0) {
              this.queryParam.statusIn = filters.status.join(','); // 状态筛选
            } else {
              this.queryParam.statusIn = '';
            }
            this.filteredInfo = filters;
            this.ipagination = pagination;
            this.loadData();
        },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
@import '~@views/library/hteFile.less';
@import '~@views/library/clearSoln/index.less';
.page-main{
  height: auto;
}
.page-main .container {
  // padding: 25px 125px 100px;
  height: auto;
}
.page-main .banner {
  background-image: url(../../../assets/contract-top.png);
}
.targetRed{
  color: #f50 !important
}
.text-over{color: #646566;overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;      
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
      overflow-wrap: break-word;
      /* min-height: 50px; */
    }
</style>
